import store from '@/store'

const debounce = {
  inserted: function (el, binding) {
    // 点击
    el.addEventListener("click", () => {

    });
  }
}

const onlyNum = {
  // 当被绑定的元素插入到 DOM 中时……
  inserted: function (el, binding, vnode, oldVnode) {
    let ele = el.tagName === 'INPUT' ? el : el.querySelector('input')
    ele.addEventListener("input", function () {
      //进行验证
      onlyNum(ele);
    });
    function onlyNum(el) {
      let val = el.value;
      val = val.replace(/[^\d.]/g, ""); //清除"数字"和"."以外的字符
      val = val.replace(/^\./g, ""); //验证第一个字符是数字
      val = val.replace(/\.{2,}/g, "."); //只保留第一个, 清除多余的
      val = val.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
      val = val.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3'); //只能输入两位个小数
      if (val != el.value) {// 跳出循环
        el.value = val;
        el.dispatchEvent(new Event("input"));//调用input事件使vue v-model绑定更新
      }
    }
  }
}

// <input type="number" v-only-number={
// 	max:'999',最大值
// 	min:'0',最小值
// 	precision:'0',保留几位小数
// 	noZero:true,为空的时候是0还是字符串
// }
// >
// v-only-number = "{ max:'999',min:'0',precision:'0',noZero:true }"
const onlyNumber = {
  // 当被绑定的元素插入到 DOM 中时……
  inserted: function (el, binding, vNode) {
    el.vDir = binding
    // vDir.value 有指令的参数
    let content
    // 设置输入框的值,触发input事件,改变v-model绑定的值
    const setVal = val => {
      if (vNode.componentInstance) {
        // 如果是自定义组件就触发自定义组件的input事件
        vNode.componentInstance.$emit('input', val)
      } else {
        // 如果是原生组件就触发原生组件的input事件
        el.value = val
        el.dispatchEvent(new Event('input'))
      }
    }
    // 输入框输入时
    el.addEventListener('input', event => {
      const vDir = el.vDir
      const e = event || window.event
      content = e.target.value
      if (!content) {
        return
      }
      let arg_max = ''
      let arg_min = ''
      if (vDir.value) {
        arg_max = parseFloat(vDir.value.max)
        arg_min = parseFloat(vDir.value.min)
      }
      if (arg_max !== undefined && content > arg_max) {
        setVal(arg_max)
        content = arg_max
        return
      }
      if (arg_min !== undefined && content < arg_min) {
        setVal(arg_min)
        content = arg_min
        return
      }
      let arg_precision = 0 // 默认保留至整数
      if (vDir.value.precision) {
        arg_precision = parseFloat(vDir.value.precision)
      }
      const reg = RegExp(`(?<=\\.\\d{${arg_precision}}).*$`)
      content = String(content).replace(reg, '')
      setVal(content)
    })
    // 按键按下=>只允许输入 数字/小数点/减号
    el.addEventListener('keypress', event => {
      const e = event || window.event
      const inputKey = String.fromCharCode(typeof e.charCode === 'number' ? e.charCode : e.keyCode)
      const re = /\d|\./
      content = e.target.value
      // 定义方法,阻止输入
      function preventInput() {
        if (e.preventDefault) {
          e.preventDefault()
        } else {
          e.returnValue = false
        }
      }
      if (!re.test(inputKey) && !e.ctrlKey) {
        preventInput()
      } else if (content.indexOf('.') > 0 && inputKey === '.') {
        // 已有小数点,再次输入小数点或者只允许输入整数
        preventInput()
      }
    })
    // 输入框失去焦点时
    el.addEventListener('focusout', event => {
      const vDir = el.vDir
      const e = event || window.event
      content = parseFloat(e.target.value)
      if (!content) {
        content = vDir.value.noZero ? '' : 0 // vDir.value.noZero 可以清空输入框，不填充0
      }
      let arg_precision = 0 // 默认保留至整数
      if (vDir.value.precision) {
        arg_precision = parseFloat(vDir.value.precision)
      }
      const reg = RegExp(`(?<=\\.\\d{${arg_precision}}).*$`)
      content = String(content).replace(reg, '')
      setVal(content)
    })
  }

}
// 自定义指令，解决el-select默认值不可删除问题
const defaultSelect =
{
  update(el, bindings) {
    const [defaultValues, selectValue] = bindings.value
    // console.log('defaultValues',defaultValues)
    // console.log('selectValue',selectValue)
    // 需要隐藏的标签索引
    const indexs = []
    if (selectValue) {
      selectValue.map((item, index) => {
        defaultValues.map(defaultItem => {
          if (item == defaultItem) {
            indexs.push(index)
          }
        })
      })
      const dealStyle = function (tags) {
        tags.forEach((el, index) => {
          if (
            indexs.includes(index) &&
            ![...el.classList].includes('select-tag-close-none')
          ) {
            el.style.display = 'none' // close 图标隐藏掉
          }
        })
      }
      // 设置样式隐藏close icon
      let tags = el.querySelectorAll('.el-tag__close')
      if (tags.length === 0) {
        // 初始化tags为空处理
        setTimeout(() => {
          let tagTemp = el.querySelectorAll('.el-tag__close')
          dealStyle(tagTemp)
        })
      } else {
        setTimeout(() => {
          dealStyle(tags)
        })
      }
    }

  }
}

const hasAuth = {
  inserted(el, binding, vnode, oldVnode) {
      const permissionCode = store.getters.permissionCode;
      const user = store.getters;
      // console.log('user',user)
      const { value } = binding
      let rules = permissionCode ? permissionCode : []
      let v = rules.find(item => item.perms === value)
      if (!v) {
          //移除元素
          el.parentNode.removeChild(el)
      }
  }
}

export { onlyNum, onlyNumber, defaultSelect,hasAuth }